package com.supor.aiot.food.adapter;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.text.TextUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.config.Config;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;

import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.food.R;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.RecommondRecipeBean;
import com.supor.aiot.food.ui.food.FoodFragment;
import com.supor.aiot.food.utils.VideoScrollPlayerManager;
import com.supor.md_video.tools.TextureVideoViewOutlineProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zook
 */
public class RecomondRecipeAdapter extends BaseMultiItemQuickAdapter<RecipeHotBean, BaseViewHolder>
        implements LoadMoreModule {
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private int oldPosition;
    private int currentViewPosition;
    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener afChangeListener;
    private int scrollPlayState = -1;
    private boolean isInited;

    public RecomondRecipeAdapter() {
        super(new ArrayList<>());
        addChildClickViewIds(R.id.iv_recipe_voice, R.id.ll_rep_sub, R.id.ll_rep_like);
        addItemType(RecipeHotBean.TYPE_ITEM_LOAD, R.layout.item_recomond_recipe_load);
        addItemType(RecipeHotBean.TYPE_ITEM, R.layout.item_recomond_recipe);
        addItemType(RecipeHotBean.TYPE_LOAD, R.layout.foot_sideslip_recipe);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder holder, RecipeHotBean recipeHotBean) {
        if (recipeHotBean.getItemType() == RecipeHotBean.TYPE_ITEM) {
            holder.setVisible(R.id.iv_recomond_recipe, true);
            holder.setVisible(R.id.rl_tag_new, recipeHotBean.getIsNew() == 0);
            Glide.with(getContext()).load(recipeHotBean.getImageVertical()).placeholder(new ColorDrawable(getContext().getResources().getColor(R.color.white_f5f5f5))).into((ImageView) holder.getView(R.id.iv_recomond_recipe));
            if (!TextUtils.isEmpty(recipeHotBean.getRecipeName())) {
                holder.setText(R.id.tv_recipe_title, recipeHotBean.getRecipeName());
            }
            TextView tvRd = holder.getView(R.id.tv_recipe_device);
            if (!TextUtils.isEmpty(recipeHotBean.getProductName()) && !TextUtils.isEmpty(recipeHotBean.getModelId())) {
                tvRd.setVisibility(View.VISIBLE);
                tvRd.setText(recipeHotBean.getCrmModelName());
            } else {
                tvRd.setVisibility(View.GONE);
            }
            holder.setText(R.id.tv_recipe_like, recipeHotBean.getLikeCount() + "");
            holder.setText(R.id.tv_recipe_store, recipeHotBean.getFavoriteCount() + "");

            holder.setBackgroundResource(R.id.iv_recipe_voice, recipeHotBean.getLocalIsMuteEnb() == 0 ?
                    R.mipmap.play_voice_mute : R.mipmap.play_voice_icon);


            PLVideoTextureView videoView = holder.getView(R.id.video_view);
            AVOptions options = new AVOptions();
            options.setInteger(AVOptions.KEY_FAST_OPEN, 1);
            options.setString(AVOptions.KEY_CACHE_DIR, getContext().getCacheDir().getAbsolutePath());
            options.setString(AVOptions.KEY_CACHE_EXT, MimeTypeMap.getFileExtensionFromUrl(recipeHotBean.getHighVertical()));
            videoView.setAVOptions(options);


            videoView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
            videoView.setLooping(true);
            videoView.setOutlineProvider(new TextureVideoViewOutlineProvider(getContext().getResources().getDimensionPixelOffset(R.dimen.dp_10)));
            videoView.setClipToOutline(true);
            videoView.setVideoPath(recipeHotBean.getHighVertical());

            holder.setBackgroundResource(R.id.iv_recipe_like, recipeHotBean.getIsLike() == 1 ? R.mipmap.like_icon_clicked : R.mipmap.like_icon_none)
                    .setBackgroundResource(R.id.iv_recipe_store, recipeHotBean.getFavoriteType() == 1 ? R.mipmap.stored_icon : R.mipmap.ic_recipe_sub_gary)
            ;

        }
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull BaseViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        if (getData().size() > holder.getLayoutPosition()) {
            if (getData().get(holder.getLayoutPosition()).getItemType() == RecipeHotBean.TYPE_ITEM) {
                try {
                    ((PLVideoTextureView) holder.getView(R.id.video_view)).pause();
                } catch (Exception e) {

                }
            }
        }
    }

    public void startVideoPlay(int position) {
        stopListPlay();

        if (position >= 0 && getData().size() > position
                && getData().get(position).getItemType() == RecipeHotBean.TYPE_ITEM
                && null != getViewByPosition(position, R.id.video_view)
                && !((PLVideoTextureView) getViewByPosition(position, R.id.video_view)).isPlaying()) {
            PLVideoTextureView currentVideView = (PLVideoTextureView) getViewByPosition(position, R.id.video_view);
            if (null != currentVideView) {
                currentVideView.setVolume(getData().get(position).getLocalIsMuteEnb(), getData().get(position).getLocalIsMuteEnb());
                if (GlobalDataCache.homeIndex == FoodFragment.INDEX_IN_HOME) {
//                    @dimen/dp_415
//                    if (currentVideView.getLayoutParams().height
//                            < getContext().getResources().getDimensionPixelOffset(R.dimen.dp_415)) {
//                        currentVideView.getLayoutParams().height = getContext().getResources().getDimensionPixelOffset(R.dimen.dp_415);
//                        currentVideView.requestLayout();
//                    }
                    currentVideView.start();
                }
            }
            oldPosition = position;
            isInited = true;
        }
    }

    public void stopListPlay() {
        if (oldPosition < 0) {
            return;
        }
        if (getData().size() > oldPosition && getData().get(oldPosition).getItemType() == RecipeHotBean.TYPE_ITEM) {
            PLVideoTextureView plVideoTextureView = (PLVideoTextureView) getViewByPosition(oldPosition, R.id.video_view);
            if (null != plVideoTextureView) {
                if (plVideoTextureView.isPlaying()) {
                    getAudioFocus();
                    plVideoTextureView.pause();
                }
            }
        }
    }

    public void release() {
        stopListPlay();
        oldPosition = 0;
        currentViewPosition = 0;
        scrollPlayState = -1;
        isInited = false;
    }

    private void getAudioFocus() {
        if (null == audioManager) {
            audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        }
        if (null == audioManager) {
            afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int focusChange) {
                    if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                        stopListPlay();
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    }
                }
            };
        }

        // Request audio focus for playback
        int result = audioManager.requestAudioFocus(afChangeListener,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);
        Logc.d("Audio_Focus", "result = " + result);

//        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//
//        }
    }

    public void bindRecView(RecyclerView recyclerView) {
        this.mRecyclerView = recyclerView;
        this.mLinearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Logc.d("onScrollStateChanged_debug RecyclerView.SCROLL_STATE_IDLE");
                    if (mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() < 0) {
                        stopListPlay();
                        return;
                    }

                    currentViewPosition = mLinearLayoutManager.findFirstCompletelyVisibleItemPosition();
                    if (currentViewPosition == oldPosition) {
                        PLVideoTextureView plVideoTextureView = (PLVideoTextureView) getViewByPosition(oldPosition, R.id.video_view);
                        if (null != plVideoTextureView && plVideoTextureView.isPlaying() ||
                                getData().get(currentViewPosition).getItemType() == RecipeHotBean.TYPE_LOAD) {
                            return;
                        }
                    }

                    if (currentViewPosition >= 0) {
                        startVideoPlay(currentViewPosition);
                    } else {
                        stopListPlay();
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                startListPlay();
            }
        });

    }

    public void onPause() {
        if (currentViewPosition >= 0) {
            stopListPlay();
        }
    }

    public void onResume() {
        if (currentViewPosition >= 0) {
            startVideoPlay(currentViewPosition);
        }
    }

    public void setVolume(int position, float volume) {
        if (position >= 0 && getData().size() > position
                && getData().get(position).getItemType() == RecipeHotBean.TYPE_ITEM
                && null != getViewByPosition(position, R.id.video_view)) {
            PLVideoTextureView currentVideView = (PLVideoTextureView) getViewByPosition(position, R.id.video_view);
            if (null != currentVideView) {
                currentVideView.setVolume(volume, volume);
            }
        }
    }


    public void pauseOnViewHide() {
        if (scrollPlayState != 1) {
            scrollPlayState = 1;
            stopListPlay();
        }
    }

    public void resumeOnViewShow() {
        if (isInited) {
            if (scrollPlayState == 1) {
                if (oldPosition >= 0) {
                    PLVideoTextureView plVideoTextureView = (PLVideoTextureView) getViewByPosition(oldPosition, R.id.video_view);
                    if (null != plVideoTextureView && !plVideoTextureView.isPlaying()) {
                        plVideoTextureView.start();
                        scrollPlayState = 2;
                    }
                }
            }
        }
    }

    public boolean isInited() {
        return isInited;
    }
}
